import { IObserver, ISubject } from "./Interface";

export class Subject implements ISubject {
  private observers: IObserver[] = []; // 存储观察者的列表

  private state: any; // 内部维护一个状态数据

  getState(): any {
    return this.state;
  }

  setState(state: any) {
    this.state = state; // 对内部状态进行更新
    this.notifyObservers(); // 更新完了之后通知所有的观察者
  }

  // 添加观察者
  subscribe(observer: IObserver): void {
    const isExist = this.observers.includes(observer);
    if (!isExist) {
      this.observers.push(observer);
    }
  }

  unsubscribe(observer: IObserver): void {
    const index = this.observers.indexOf(observer);
    if (index !== -1) {
      this.observers.splice(index, 1);
    }
  }

  notifyObservers(): void {
    this.observers.forEach((observer) => {
      observer.update(this.state);
    });
  }
}
